package com.xiangxiao.rpan.file.threadpool;

import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.*;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/8/17 16:56
 */
/**
 * 线程执行调度框架(自定义线程池)
 * */
public class ThreadExecutorUtils {
  @Value("${thread.pool.core}")
  private int core;
  private static int corePoolSize;
  @Value("${thread.pool.max}")
  private int max;
  private static int maximumPoolSize;
  @Value("${thread.pool.keepAlive}")
  private int keepAlive;
  private static int keepAliveTime;

  private ThreadExecutorUtils() {}

  @PostConstruct
  public void setCorePoolSize() {
    corePoolSize = this.core;
  }

  public static int getCorePoolSize() {
    return corePoolSize;
  }

  @PostConstruct
  public void setMaximumPoolSize() {
    maximumPoolSize = this.max;
  }

  public static int getMaximumPoolSize() {
    return maximumPoolSize;
  }

  @PostConstruct
  public void setKeepAliveTime() {
    keepAliveTime = this.keepAlive;
  }

  public static int getKeepAliveTime() {
    return keepAliveTime;
  }

  private static ThreadPoolExecutor executor =
      new ThreadPoolExecutor(getCorePoolSize(), getMaximumPoolSize(), getKeepAliveTime(), TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000));

  /**
   * 无返回任务执行
   * @param runnable 任务
   */
  public static void execute(Runnable runnable) {
    executor.execute(runnable);
  }

  /**
   * 有结果的返回
   * @param callable 任务
   * @param <V> v
   * @return 结果
   */
  public static <V> Future<V> call(Callable<V> callable) {
    return executor.submit(callable);
  }

  /**
   * 调用批量任务
   * @param tasks 任务
   * @param <V> v
   * @return 结果
   */
  public static <V> List<Future<V>> invokeAll(List<Callable<V>> tasks) throws Exception {
    try {
      return executor.invokeAll(tasks);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new Exception(e.getMessage());
    }
  }
}
